#include "Log.h"

Log* Log::pInstance = NULL;

Log* Log::Inst(){
  if(pInstance == NULL){
	  pInstance = new Log();
  }
  return pInstance;
}

Log::Log(){ // constructor
  //Initialize(); // you can ignore this function
	
	DEBUG_LEVEL = 100;

	struct tm *timeInitPtr;
	time_t t1 = time( NULL );
	timeInitPtr = gmtime(&t1);

	/*
		nota: tm_hour tiene 1 horas menos.
	*/

	if(timeInitPtr->tm_hour == 22)
		timeInitPtr->tm_hour = 23;
	else if(timeInitPtr->tm_hour == 23)
		timeInitPtr->tm_hour = 0;
	else
		timeInitPtr->tm_hour +=1;

	printf( "Comienzo: %s\n", asctime(timeInitPtr) );
	char temp[200];
	memset(nameLogFile,0,sizeof(nameLogFile));
	memset(temp,0,sizeof(temp));
	strcpy(nameLogFile,asctime(timeInitPtr));
	for(int i=0; i<strlen(nameLogFile); i++)
	{
		if (nameLogFile[i]=='\n')
			temp[i] = '\0';
		else if(nameLogFile[i]==' ')
			temp[i] = '_';		
		else if(nameLogFile[i]==':')
			temp[i] = '-';
		else
			temp[i] = nameLogFile[i];
	}
	memset(nameLogFile,0,sizeof(nameLogFile));
	system("mkdir logs");
	strcpy(nameLogFile,"./logs/LOG_CLIENT_");
	strcat(nameLogFile,temp);
	strcat(nameLogFile,".txt");

	logfile = fopen(nameLogFile,"a");
}

Log::~Log(){
  if(pInstance != 0)delete pInstance;
}
void Log::logRes(int depth, char * nameFunction, int levelMessage, char *message, ...)
{ 
	logfile = fopen(nameLogFile, "a");
	if (levelMessage <= DEBUG_LEVEL){
		
		for(int i=0; i<depth; i++)
			fprintf(logfile,"   ");

		va_list arg; 
		
		fprintf(logfile, "%s:%d:", nameFunction, levelMessage); 

		va_start(arg, message); 
		vfprintf(logfile, message, arg); 
		va_end(arg); 

		fprintf(logfile, "\n"); 
	}

	fclose(logfile);
} 
